package com.tiorb.imageeffect;

import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

/**
 * 控制Toast显示 新的Toast到来时，取消前一个显示
 *  Create By Logan Tao
 *
 */
public class ToastUtils {

    public static final int LENGTH_SHORT = 1000;
    public static final int LENGTH_LONG = 3000;

    private static Toast mToast;
    private static Toast mViewToast;
    private static Handler mHandler = new Handler();
    private static Runnable toastCel = new Runnable() {
        public void run() {
            if (mToast != null) {
                mToast.cancel();
            }
        }
    };

    /**
     * @param mContext
     * @param text
     * @param duration CustomToast LENGTH_SHORT 1秒<br/>
     *                 CustomToast LENGTH_LONG 3秒
     */
    public static void showToast(Context mContext, String text, int duration) {
        if (duration <= 1) {
            duration = LENGTH_SHORT;
        }
        // mHandler.removeCallbacks(toastCel);
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }

        if (duration == LENGTH_LONG) {
            mToast = Toast.makeText(mContext, text, Toast.LENGTH_LONG);
        } else {
            mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
        }
        // mHandler.postDelayed(toastCel, duration);
        mToast.show();
    }

    public static void showToast(Context mContext, int resId, int duration) {
        showToast(mContext, mContext.getResources().getString(resId), duration);
    }

    public static void showToast(Context mContext, int resId) {
        showToast(mContext, mContext.getResources().getString(resId), LENGTH_LONG);
    }

    public static void showToast(Context mContext, String text) {
        showToast(mContext, text, LENGTH_LONG);
    }

    public static void showViewToast(Context mContext, int layoutId, int duration) {
        mHandler.removeCallbacks(toastCel);
        if (mViewToast == null) {
            mViewToast = new Toast(mContext);
        }
        View view = View.inflate(mContext, layoutId, null);
        mViewToast.setView(view);
        mViewToast.setGravity(Gravity.CENTER, 0, 0);// 起点位置为中间 100为向下移100dp
        mViewToast.show();
        mHandler.postDelayed(toastCel, duration);
    }
}
